import 'dart:io';
import 'dart:typed_data';

import 'package:cloudapp/esdk/db.dart';
import 'package:cloudapp/esdk/esync.dart';
import 'package:cloudapp/esdk/model/local_album.dart';
import 'package:cloudapp/model/global_info.dart';
import 'package:cloudapp/pages/base.dart';
import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';

class LocalAlbumInfo {
  final String id;
  final String name;
  Uint8List thumb;
  final int assetCount;
  bool beSync = false;

  LocalAlbumInfo({this.id, this.name, this.thumb, this.assetCount});

  String getIdentify() {
    if(Platform.isIOS) {
      return this.name;
    }
    return this.id;
  }
}

class LocalAlbumItemWidget extends StatefulWidget {
  final LocalAlbumInfo info;
  LocalAlbumItemWidget({Key key, @required this.info}): super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _LocalAlbumItem();
  }
}

const albumImgSize = 64.0;

class _LocalAlbumItem extends BaseState<LocalAlbumItemWidget> {
  @override
  Widget build(BuildContext context) {
    // 如果 thumb 为空
    Widget img;
    var info = widget.info;
    if(info.thumb == null || info.thumb.length == 0) {
      img = Image.asset(
        'res/images/album.png',
        width: albumImgSize,
        height: albumImgSize,
      );
    } else {
      img = Image.memory(
        info.thumb,
        width: albumImgSize,
        height: albumImgSize,
      );
    }

    return Row(
      children: <Widget>[
        Checkbox(
          value: widget.info.beSync,
          onChanged: (v) {
            // 修改待同步相册
            modifySyncAlbums(v);
          },
        ),
        Container(
          margin: const EdgeInsets.fromLTRB(0, 2, 6, 2),
          child: img,
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              info.name
            ),
            Text(
              '${info.assetCount} 个文件'
            )
          ],
        )
      ],
    );
  }

  /*
1. 查找终端ID，若为0则请求服务器获取
2. 查找相册ID
   */
  Future<int> fetchServerAlbum(String albumName) async {
    var gInfo = GlobalInfo.i();
    if(gInfo.deviceId == 0) {
      var devId = await fetchDeviceId();
      gInfo.setDeviceId(devId);
    }

    return await ESync.i().fetchAlbumId(gInfo.deviceId, albumName);
  }

  /// 修改待同步相册逻辑：
  /// 1. 获取相册唯一标识符，此唯一应是本地唯一
  /// 2. 数据库查找 local_album 表
  ///   1. 若找到，且动作为删除，则删除此记录
  ///   2. 若未找到，且动作是新增，则新增记录
  /// 3. 成功则UI更新
  Future<void> modifySyncAlbums(bool nVal) async {
    var sessionId = GlobalInfo.i().sessionId;
    await loading(() async {
      var info = widget.info;
      var localAlbumId = info.getIdentify();
      var albums = await DbStorage.i().findLocalAlbum(sessionId, localAlbumId);
      if(albums.length > 0 && nVal == false) {
        // 删除此记录
        print('found record, remove it.');
        await DbStorage.i().removeLocalSyncAlbum(localAlbumId);
      } else if(albums.length == 0 && nVal == true) {
        // 新增一条记录
        print('cannot found, insert new record.');
        var serverId = await fetchServerAlbum(info.name);
        // 首先应从服务器获取其相册ID
        await DbStorage.i().addLocalSyncAlbum(LocalAlbum(
          id: null,
          albumId: localAlbumId,
          serverId: serverId,
          sessionId: sessionId,
        ));
      } else {
        print('ignore it.');
      }
      setState(() {
        widget.info.beSync = nVal;
      });
    });
  }

  /*
manufacturer HUAWEI
model EVA-AL00
   */
  Future<int> fetchDeviceId() async {
    var devInfo = DeviceInfoPlugin();
    AndroidDeviceInfo info = await devInfo.androidInfo;
    var brand = info.manufacturer;
    var model = info.model;
    var hash = "$brand $model";
    return await ESync.i().fetchDeviceId(brand, model, hash);
  }
}
